package com.book.business.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.book.business.entity.BookCart;
import com.book.business.entity.BookIndent;
import com.book.business.entity.BookSell;
import com.book.business.service.BookCartService;
import com.book.business.service.BookIndentService;
import com.book.business.service.BookSellService;
import com.book.buyout.service.PrelistingService;
import com.book.common.annotation.ControllerEndpoint;
import com.book.common.annotation.Log;
import com.book.common.controller.BaseController;
import com.book.common.entity.FebsConstant;
import com.book.common.entity.FebsResponse;
import com.book.common.entity.QueryRequest;
import com.book.common.utils.BookMethod;
import com.book.common.utils.FebsUtil;
import com.book.common.utils.WareBook;
import com.book.shelves.entity.BookStore;
import com.book.shelves.service.BookStoreService;
import com.book.system.entity.Money;
import com.book.system.entity.User;
import com.book.system.service.IUserService;
import com.book.system.service.MoneyService;
import com.book.warehouse.entity.WarehouseBook;
import com.book.warehouse.entity.WarehouseHouse;
import com.book.warehouse.entity.WarehouseHouseBook;
import com.book.warehouse.service.WarehouseBookService;
import com.book.warehouse.service.WarehouseHouseBookService;
import com.book.warehouse.service.WarehouseHouseService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: 盛佳帅
 * @Description:  20173953
 */

@Controller
public class BookCartController extends BaseController {
    @Autowired
    BookCartService bookCartService;
    @Autowired
    PrelistingService prelistingService;
    @Autowired
    BookIndentService bookIndentService;
    @Autowired
    BookSellService bookSellService;
    @Autowired
    MoneyService moneyService;
    @Autowired
    IUserService userService;
    @Autowired
    WarehouseBookService warehouseBookService;
    @Autowired
    BookStoreService bookStoreService;
    @Autowired
    WarehouseHouseBookService warehouseHouseBookService;
    @Autowired
    WarehouseHouseService warehouseHouseService;

    @GetMapping(FebsConstant.VIEW_PREFIX + "business/bookCart")
    public String bookCartIndex() {
        return FebsUtil.view("business/cart/bookCartList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "business/bookCart/update/{id}")
    public String bookCartUpdate(@PathVariable Integer id, ModelMap modelMap) {
        BookCart bookCart = this.bookCartService.getById(id);
        modelMap.put("bookCart", bookCart);
        return FebsUtil.view("business/cart/bookCartUpdate");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "business/bookCart/cart/{id}")
    public String bookCartCart(@PathVariable Integer id, ModelMap modelMap) {
        BookCart bookCart = this.bookCartService.getById(id);
        modelMap.put("bookCart", bookCart);
        return FebsUtil.view("business/cart/bookCart");
    }

    @GetMapping("bookCart")
    @ResponseBody
    @RequiresPermissions("bookCart:view")
    public FebsResponse bookCartList(BookCart bookCart) {
        return new FebsResponse().success().data(this.bookCartService.findBookCart(bookCart));
    }

    @Log("访问购物车")
    @GetMapping("bookCart/list")
    @ResponseBody
    @RequiresPermissions("bookCart:view")
    public FebsResponse bookCartIPage(QueryRequest request, BookCart bookCart) {
        Map<String, Object> dataTable = getDataTable(this.bookCartService.pageBookCart(request, bookCart));
        return new FebsResponse().success().data(dataTable);
    }

    @Log("购物车-修改")
    @PostMapping("bookCart/update")
    @ResponseBody
    @RequiresPermissions("bookCart:update")
    @ControllerEndpoint(operation = "修改书籍信息成功", exceptionMessage = "修改书籍信息失败")
    public FebsResponse bookCartUpdate(BookCart bookCart) {
        return new FebsResponse().message("您无此权限，请联系出版社管理员");
    }


    @Log("购物车-支付")
    @PostMapping("bookCart/pay/{ids}")
    @ResponseBody
    @RequiresPermissions("bookCart:pay")
    @ControllerEndpoint(operation = "支付成功", exceptionMessage = "支付失败")
    public FebsResponse bookCartPay(@PathVariable String ids, Money money) {
        User user = userService.findByName(getCurrentUser().getUsername());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        Calendar calender = Calendar.getInstance();
        String yearAndMonths = format.format(calender.getTime());
        String[] yearAndMonth = yearAndMonths.split("-");
        if (user.getAddress() == null || user.getMobile() == null) {
            return new FebsResponse().message("请先填写个人信息");
        }
        String[] attr = ids.split(",");
        List<BookCart> cartList = bookCartService.payBookCart(attr);
        for (int i = 0; i < cartList.size(); i++) {
            String uuid = BookMethod.getUUID();
            BookSell bookSell = bookSellService.getOne(new QueryWrapper<BookSell>().lambda()
                    .eq(BookSell::getBookname, cartList.get(i).getBookname())
                    .eq(BookSell::getPubid, cartList.get(i).getPubid()));
            if (cartList.get(i).getNumber() == 0) {
                return new FebsResponse().message("不能购买0本书籍！");
            }
            if (bookSell == null) {
                return new FebsResponse().message("非常抱歉！该书籍已下架！");
            }
            if (user.getMoney() < (cartList.get(i).getBookmoney() * cartList.get(i).getNumber())) {
                return new FebsResponse().message("余额不足，请先进行充值！");
            }
            BookIndent bookIndent = bookIndentService.getOne(new QueryWrapper<BookIndent>().lambda()
                    .eq(BookIndent::getBookname, cartList.get(i).getBookname())
                    .eq(BookIndent::getPubid, cartList.get(i).getPubid())
                    .eq(BookIndent::getPay, 0));
            if (bookIndent != null) {
                return new FebsResponse().message("您的订单中还有相同类型书籍未支付！");
            }
            bookIndent = new BookIndent()
                    .setPay("1").setUsername(user.getUsername()).setAddress(user.getAddress())
                    .setPhone(user.getMobile()).setOnetime(new Date())
                    .setBookname(cartList.get(i).getBookname())
                    .setPubid(cartList.get(i).getPubid())
                    .setType(cartList.get(i).getType())
                    .setMessage(cartList.get(i).getMessage())
                    .setBookmoney(cartList.get(i).getBookmoney())
                    .setNumber(cartList.get(i).getNumber())
                    .setMoney(cartList.get(i).getBookmoney() * cartList.get(i).getNumber())
                    .setYear(yearAndMonth[0])
                    .setMonth(yearAndMonth[1])
                    .setFlag("0")
                    .setBackstatus("0")
                    .setStatus("0")
                    .setOmit("1")
                    .setBookindentid(uuid);
            bookSell.setCart(0);
            Integer payM = cartList.get(i).getBookmoney() * cartList.get(i).getNumber();
            money.setUsername(user.getUsername())
                    .setType("0")
                    .setPayment(payM)
                    .setOmit("0")
                    .setBookindentid(uuid);
            user.setMoney(user.getMoney() - payM);
            if (bookSell.getNumber() <= 0) {
                return new FebsResponse().message("十分抱歉！" + bookIndent.getBookname() + ",已售空");
            }
            if (bookIndent.getNumber() > bookSell.getNumber()) {
                return new FebsResponse().message(bookIndent.getBookname() + "预售还有" + bookSell.getNumber() + "本，请调购买数量！");
            }
            bookSellService.updateBookSell(bookSell);
            WareBook.wareBookChange(cartList.get(i).getBookname(),"减少",cartList.get(i).getNumber());
            bookIndentService.addBookIndent(bookIndent);
            bookCartService.removeById(cartList.get(i).getId());
            moneyService.addMoney(money);
            userService.updateMoney(user);
        }
        return new FebsResponse().success();
    }

    @Log("购物车-删除")
    @PostMapping("bookCart/delete/{ids}")
    @ResponseBody
    @RequiresPermissions("bookCart:delete")
    @ControllerEndpoint(operation = "删除书籍信息成功", exceptionMessage = "删除书籍信息失败")
    public FebsResponse bookCartdelete(@PathVariable String ids) {
        String[] attr = ids.split(",");
        List<BookCart> cartList = bookCartService.payBookCart(attr);
        for (int i = 0; i < cartList.size(); i++) {
            BookSell bookSell = bookSellService.getOne(new QueryWrapper<BookSell>().lambda()
                    .eq(BookSell::getBookname, cartList.get(i).getBookname())
                    .eq(BookSell::getPubid, cartList.get(i).getPubid()));
            if (bookSell != null) {
                bookSell.setCart(0);
                bookSellService.updateBookSell(bookSell);
            }
        }
        this.bookCartService.deleteBookCart(attr);
        return new FebsResponse().success();
    }
}